package jp.sourceforge.talisman.mds.io;

/*
 * $Id: MdsTableParser.java,v 1.1 2009/09/12 05:06:19 weiwei Exp $
 */

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

import jp.sourceforge.talisman.csvio.CsvLine;
import jp.sourceforge.talisman.csvio.CsvParser;
import jp.sourceforge.talisman.mds.Table;

/**
 * 
 * @author Haruaki Tamada
 * @version $Revision: 1.1 $ 
 */
public class MdsTableParser{
    public CsvParser parser;
    private boolean header = true;

    public MdsTableParser(CsvParser parser){
        this.parser = parser;
    }

    public MdsTableParser(InputStream in){
        this(new InputStreamReader(in));
    }

    public MdsTableParser(Reader in){
        this(new CsvParser(new BufferedReader(in)));
    }

    public boolean hasHeader(){
        return header;
    }

    public void setHeader(boolean header){
        this.header = header;
    }

    public Table<String> parse() throws IOException{
        CsvLine[] lines = parser.getAllLines();

        Table<String> table = new Table<String>();
        String[] names = null;
        int index = 0;
        if(hasHeader()){
            index = 1;
            names = lines[0].getValues();
        }

        for(int i = index; i < lines.length; i++){
            String[] values = lines[i].getValues();
            if(hasHeader()){
                for(int j = 1; j < values.length; j++){
                    if(!values[j].trim().equals("")){
                        table.addValue(values[0], names[j], new Double(values[j]));
                    }
                }
            }
            else{
                for(int j = 0; j < values.length; j++){
                    if(!values[j].trim().equals("")){
                        table.addValue(
                            String.valueOf(i), String.valueOf(j), new Double(values[j])
                        );
                    }
                }
            }
        }
        return table;
    }
}
